package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.dto.CategoryPageQueryDTO;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.Category;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.CategoryMapper;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.result.PageResult;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private CategoryMapper categoryMapper;
    //微信接口信息
    private static final String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";
    //调用微信接口信息，获取openid
    private String getOpenid(String code) {
        //获取参数列表
        Map<String,String> map=new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",code);
        map.put("grant_type","authorization_code");
        //返回结果为JSON格式字符串
        String json = HttpClientUtil.doGet(WX_LOGIN_URL, map);
        //将JSON格式字符串转换为JSON对象
        JSONObject jsonObject = JSON.parseObject(json);
        //获取用户的openid
        String openid = jsonObject.getString("openid");
        return openid;
    }
    //微信登录
    public User wxlogin(UserLoginDTO userLoginDTO) {
        String openid = getOpenid(userLoginDTO.getCode());
        //判断openid是否为空，为空则登录失败
        if(openid==null) throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
            //判断当前用户是否为新用户,如果不是，自动完成注册
         User user = userMapper.getByOpenid(openid);
        if(user==null){
            user=new User();
            user.setCreateTime(LocalDateTime.now());
            user.setOpenid(openid);
            userMapper.insert(user);
        }
            //返回用户信息
        return user;
    }

}
